import { NextResponse } from "next/server"
import { getMessages, createMessage, getNewMessages } from "@/lib/neon-db"

export async function GET(request: Request) {
  try {
    const url = new URL(request.url)
    const lastMessageId = url.searchParams.get("lastMessageId")

    let messages
    if (lastMessageId) {
      messages = await getNewMessages(lastMessageId)
    } else {
      messages = await getMessages(100)
    }

    return NextResponse.json({ messages })
  } catch (error) {
    console.error("Error in GET /api/messages:", error)
    return NextResponse.json({ error: "Failed to fetch messages" }, { status: 500 })
  }
}

export async function POST(request: Request) {
  try {
    const { userId, content } = await request.json()

    if (!userId || !content) {
      return NextResponse.json({ error: "User ID and content are required" }, { status: 400 })
    }

    const message = await createMessage(userId, content)

    return NextResponse.json({ message })
  } catch (error) {
    console.error("Error in POST /api/messages:", error)
    return NextResponse.json({ error: "Failed to create message" }, { status: 500 })
  }
}
